package com.cgt.xiaotao.user.controller;

import com.cgt.common.utils.BeanUtils;
import com.cgt.common.utils.R;
import com.cgt.xiaotao.user.domain.dto.UserAddressDTO;
import com.cgt.xiaotao.user.domain.po.UserAddress;
import com.cgt.xiaotao.user.service.IUserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户地址接口")
@Slf4j
@RestController
@RequestMapping("/address")
@RequiredArgsConstructor
public class UserAddressController {
    private final IUserAddressService userAddressService;

    @ApiOperation("新增收获地址")
    @PostMapping("/save")
    public R<String> saveAddress(@RequestBody UserAddressDTO dto) {
        try {
            userAddressService.saveAddress(dto);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.fail("操作失败");
        }
    }

    @ApiOperation("更新收获地址")
    @PostMapping("/update")
    public R<String> updateAddress(@RequestBody UserAddressDTO dto) {
        try {
            userAddressService.updateAddress(dto);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.fail("操作失败");
        }
    }

    @ApiOperation("查询收获地址列表")
    @GetMapping("/list")
    public R<List<UserAddressDTO>> getList() {
        List<UserAddressDTO> list =  userAddressService.getList();
        return R.ok(list);
    }

    @ApiOperation("删除收获地址")
    @DeleteMapping("/{id}")
    public R<String> deleteAddress(@PathVariable Long id) {
        userAddressService.deleteAddress(id);
        return R.ok("删除成功");
    }

    @ApiOperation("查询收获地址")
    @GetMapping("/{id}")
    public UserAddressDTO getAddress(@PathVariable Long id) {
        UserAddress userAddress = userAddressService.getById(id);
        UserAddressDTO dto = BeanUtils.copyBean(userAddress, UserAddressDTO.class);
        return dto;
    }

}
